package com.itheima.health.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @Author: 位帅帅
 * @Date: 10:38 2021/1/11
 * @Description: 配置用户
 */
//@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //用户详情,创建一个配置类
        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> configure = auth.inMemoryAuthentication();
        //配置三个用户
        //密码格式:{算法}密文,noop:不加密,md5:加密
        //authorities用于提供用户的角色和权限,默认带ROLE_前缀的是角色,否则是权限
        configure.withUser("admin").password("{noop}admin").authorities("ROLE_ADMIN");
        configure.withUser("zhangsan").password("{noop}zhangsan").authorities("ROLE_01", "add");
        configure.withUser("lisi").password("{MD5}81dc9bdb52d04dc20036dbd8313ed055").authorities("ROLE_02", "find");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //指定访问控制规则
        //1-通过authorizeRequests()开启一个拦截规则
        //2_通过antMatchers指定需要拦截的资源,参数为ant表达式

        //允许所有访问
        http.authorizeRequests().antMatchers("*.js", "*.css").access("permitAll()");
        //允许拥有"add"权限和"ROLE_ADMIN"角色的人访问
        http.authorizeRequests().antMatchers("/pages/checkitem.html").access("hasAnyAuthority('add','ROLE_ADMIN')");
        //允许拥有"find"权限访问
        http.authorizeRequests().antMatchers("/pages/checkgroup.html").access("hasAuthority('find')");
        //允许登陆的人访问
        http.authorizeRequests().antMatchers("/main.html", "/pages/**").access("isAuthenticated()");
        //使用springSecurity默认的登陆配置
        //http.formLogin();

        //配置登录表单相关内容
        http.formLogin().loginPage("/login.html")
                .loginProcessingUrl("/sec/login")
                .failureUrl("/login-fail.html")
                .defaultSuccessUrl("/main.html");

        //关闭csrf
        http.csrf().disable();

        http.logout().logoutUrl("/sec/logout")
                .logoutSuccessUrl("/login.html")
                .invalidateHttpSession(true);
        http.exceptionHandling().accessDeniedPage("/auth-fail.html");

    }
}
